# -*- coding: utf-8 -*-  
from PaddleTools.TTS import TTSExecutor
from PaddleTools.GAN import wav2lip
import time
import os
import requests
from lxml import etree
import json
from config import Config
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, default='E:\Graduation project\PaddleBoBo-develop\default.yaml', help='config file')

def get_news(timestamp):
    timestamp = timestamp - 600
    try:
        headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
                "Cookie": "uid=wKhSYmG7/mV4wH0eAzi6Ag==; Hm_lvt_78c58f01938e4d85eaf619eae71b4ed1=1639710329; v=A5yfBb9vERPwqeXPo0txCKEbbbFLFUBwwrlUIHadqAdqwTLvniUQzxLJJJ7F"}
        news_url = "http://stock.10jqka.com.cn/20220401/c638042957.shtml"
        news_requests = requests.get(news_url,headers=headers)
        response = news_requests.text
        html = etree.HTML(response)
        newest_id = timestamp
        news_content=html.xpath('/html/body/div[4]/div[1]/h2/text()')[0]
        return newest_id, news_content
    except:
        return None, None

if __name__ == '__main__':
    args = parser.parse_args()
    _Config = Config(args.config)

    TTS = TTSExecutor(args.config)
    SAVEPATH = _Config.SavePath()
    before_news_id = None

    os.environ['FLAGS_eager_delete_tensor_gb'] = "0.0"
    #一旦不再使用即释放内存垃圾，=1.0 垃圾占用内存大小达到10G时，释放内存垃圾
    FLAGS_eager_delete_tensor_gb=0.0
    #启用快速垃圾回收策略，不等待cuda kernel 结束，直接释放显存
    FLAGS_fast_eager_deletion_mode=1
    #该环境变量设置只占用0%的显存
    FLAGS_fraction_of_gpu_memory_to_use=0

    while True:
        timestamp = int(time.time())
        VIDEO_SAVE_PATH = os.path.join(SAVEPATH['VIDEO_SAVE_PATH'],f'{timestamp}.mp4')
        AUDIO_SAVE_PATH = os.path.join(SAVEPATH['AUDIO_SAVE_PATH'],f'{timestamp}.wav')

        news_id,news_content = get_news(timestamp)

        if news_id == None or news_id==before_news_id:
            #如果返回None或者与上一条相同
            pass
        else:
            wavfile = TTS.run(text=news_content,output=AUDIO_SAVE_PATH)
            video = wav2lip(_Config.GAN()['FOM_OUTPUT_VIDEO'],wavfile,VIDEO_SAVE_PATH)
            before_news_id = news_id

        time.sleep(15) #每15秒检查一次更新